import argparse
import uuid

def process_tsv(input_file, output_file, error_file):
    pred_dorado_count = 0
    bisulfite_count = 0
    
    with open(input_file, 'r') as infile, open(output_file, 'w') as outfile, open(error_file, 'w') as errfile:
        # Write header for output file
        outfile.write('read_name\tpred_pos_text\tpred_dorado_text\tbisulfite_text\tref_pos_text\n')
        # Write header for error file
        errfile.write('read_name\n')
        
        # Process each row
        for line in infile:
            row = line.strip().split('\t')
            read_name = row[0]
            pred_pos_text = row[5].split(',')
            pred_dorado_text = row[6].split(',')
            bisulfite_text = row[15].split(',')
            ref_pos_text = row[16].split(',')
            
            # Filter out entries where bisulfite_text or ref_pos_text is -1
            filtered_data = [
                (pos, dorado, bisulfite, ref)
                for pos, dorado, bisulfite, ref in zip(pred_pos_text, pred_dorado_text, bisulfite_text, ref_pos_text)
                if bisulfite != '-1'
            ]
            
            # If there are valid entries after filtering
            if filtered_data:
                filtered_pred_pos, filtered_dorado, filtered_bisulfite, filtered_ref_pos = zip(*filtered_data)
                
                # Count non -1 pred_dorado_text entries
                pred_dorado_count += sum(1 for x in filtered_dorado if x != '-1' and x != '-1.0')
                # Count non -1 bisulfite_text entries
                bisulfite_count += len(filtered_bisulfite)
                
                # Check if any pred_dorado_text is -1
                if '-1' in filtered_dorado or '-1.0' in filtered_dorado:
                    errfile.write(f'{read_name}\n')
                
                # Write filtered data to output
                outfile.write('\t'.join([
                    read_name,
                    ','.join(filtered_pred_pos),
                    ','.join(filtered_dorado),
                    ','.join(filtered_bisulfite),
                    ','.join(filtered_ref_pos)
                ]) + '\n')
    
    return pred_dorado_count, bisulfite_count

def main():
    parser = argparse.ArgumentParser(description='Process TSV file and filter out bisulfite_text and ref_pos_text entries with -1.')
    parser.add_argument('input_file', help='Input TSV file path')
    parser.add_argument('output_file', help='Output TSV file path')
    parser.add_argument('error_file', help='Error TSV file path for read_names with pred_dorado_text containing -1')
    
    args = parser.parse_args()
    
    pred_dorado_count, bisulfite_count = process_tsv(args.input_file, args.output_file, args.error_file)
    
    print(f"Number of pred_dorado_text entries not equal to -1: {pred_dorado_count}")
    print(f"Number of bisulfite_text entries not equal to -1: {bisulfite_count}")

if __name__ == '__main__':
    main()